<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="填表时间" prop="fillTime">
        <el-date-picker
          v-model="queryParams.fillTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="班级" prop="className">
        <el-input
          v-model="queryParams.className"
          placeholder="请输入班级"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="节次" prop="classSession">
        <el-input
          v-model="queryParams.classSession"
          placeholder="请输入节次"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="晚修节次" prop="eveningSession">
        <el-input
          v-model="queryParams.eveningSession"
          placeholder="请输入晚修节次"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="未入袋手机" prop="unbaggedPhones">
        <el-input
          v-model="queryParams.unbaggedPhones"
          placeholder="请输入未入袋手机数量"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="未到人数" prop="absentCount">
        <el-input
          v-model="queryParams.absentCount"
          placeholder="请输入未到人数"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="特殊请假人数" prop="specialAbsentCount">
        <el-input
          v-model="queryParams.specialAbsentCount"
          placeholder="请输入特殊请假人数"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="是否行礼" prop="isSalute">
        <el-select
          v-model="queryParams.isSalute"
          placeholder="请选择是否行礼"
          clearable
          class="!w-240px"
        >
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否点名" prop="isRollCall">
        <el-select
          v-model="queryParams.isRollCall"
          placeholder="请选择是否点名"
          clearable
          class="!w-240px"
        >
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>
      <el-form-item label="布置作业" prop="isAssignShowHomework">
        <el-select
          v-model="queryParams.isAssignShowHomework"
          placeholder="请选择是否布置作业"
          clearable
          class="!w-240px"
        >
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="queryParams.remark"
          placeholder="请输入备注"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="图片链接" prop="imageUrl">
        <el-input
          v-model="queryParams.imageUrl"
          placeholder="请输入图片链接"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="处理进度" prop="processStatus">
        <el-select
          v-model="queryParams.processStatus"
          placeholder="请选择处理进度"
          clearable
          class="!w-240px"
        >
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>
      <el-form-item label="填表人" prop="filler">
        <el-input
          v-model="queryParams.filler"
          placeholder="请输入填表人"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="更新人" prop="updateBy">
        <el-input
          v-model="queryParams.updateBy"
          placeholder="请输入更新人"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['ao:class-discipline:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['ao:class-discipline:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出明细
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExportStatistics"
          :loading="exportStatisticsLoading"
          v-hasPermi="['ao:class-discipline:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出统计表
        </el-button>
        <!-- <el-button
          type="info"
          plain
          @click="importTemplate"
          v-hasPermi="['ao:class-discipline:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 下载模板
        </el-button> -->
        <el-button
          type="warning"
          plain
          @click="handleImport"
          v-hasPermi="['ao:class-discipline:create']"
        >
          <Icon icon="ep:upload" class="mr-5px" /> 导入
        </el-button>
        <el-button
            type="danger"
            plain
            :disabled="isEmpty(checkedIds)"
            @click="handleDeleteBatch"
            v-hasPermi="['ao:class-discipline:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
        row-key="id"
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
        @selection-change="handleRowCheckboxChange"
    >
    <el-table-column type="selection" width="55" />
      <el-table-column label="记录编号" align="center" prop="recordId" />
      <el-table-column
        label="填表时间"
        align="center"
        prop="fillTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="班级" align="center" prop="className" />
      <el-table-column label="节次" align="center" prop="classSession" width="120">
        <template #default="scope">
          {{ getClassSessionByTime(scope.row.fillTime) }}
        </template>
      </el-table-column>
      <el-table-column label="晚修节次" align="center" prop="eveningSession" width="120">
        <template #default="scope">
          {{ getEveningSessionByTime(scope.row.fillTime) }}
        </template>
      </el-table-column>
      <el-table-column label="未入袋手机" align="center" prop="unbaggedPhones" />
      <el-table-column label="未到人数" align="center" prop="absentCount" />
      <el-table-column label="特殊请假人数" align="center" prop="specialAbsentCount" />
      <el-table-column label="是否行礼" align="center" prop="isSalute" />
      <el-table-column label="是否点名" align="center" prop="isRollCall" />
      <el-table-column label="布置作业" align="center" prop="isAssignShowHomework" />
      <el-table-column label="晚修作业内容" align="center" prop="eveningHomeworkContent" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="图片" align="center" prop="imageUrl" width="120">
        <template #default="scope">
          <div v-if="getImageUrl(scope.row.imageUrl)">
            <!-- 如果是草料二维码链接，显示为可点击的按钮 -->
            <el-button
              v-if="scope.row.imageUrl && scope.row.imageUrl.includes('console.cli.im')"
              type="primary"
              link
              @click="openImageInNewTab(scope.row.imageUrl)"
              style="padding: 0"
            >
              <el-icon style="margin-right: 4px"><Link /></el-icon>
              查看图片
            </el-button>
            <!-- 其他图片正常显示 -->
            <el-image
              v-else
              :src="getImageUrl(scope.row.imageUrl)"
              :preview-src-list="[getImageUrl(scope.row.imageUrl)]"
              fit="cover"
              style="width: 80px; height: 80px; cursor: pointer"
              :preview-teleported="true"
              lazy
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                  <div style="font-size: 12px; color: #999; margin-top: 4px;">加载失败</div>
                </div>
              </template>
              <template #placeholder>
                <div class="image-slot">
                  <el-icon><Loading /></el-icon>
                </div>
              </template>
            </el-image>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="处理进度" align="center" prop="processStatus" />
      <el-table-column label="填表人" align="center" prop="filler" />
      <el-table-column label="更新人" align="center" prop="updateBy" />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['ao:class-discipline:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['ao:class-discipline:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <ClassDisciplineForm ref="formRef" @success="getList" />
  
  <!-- 导入对话框 -->
  <el-dialog title="导入课堂纪律登记" v-model="importDialogVisible" width="400px" append-to-body>
    <el-form ref="importFormRef" :model="importForm" :rules="importRules" label-width="140px">
      <el-form-item label="是否更新已有数据" prop="updateSupport">
        <el-radio-group v-model="importForm.updateSupport">
          <el-radio :value="true">是</el-radio>
          <el-radio :value="false">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="导入文件" prop="file">
        <el-upload
          ref="uploadRef"
          :limit="1"
          accept=".xlsx,.xls"
          :disabled="importLoading"
          :on-change="handleFileSuccess"
          :on-error="handleFileError"
          :on-remove="handleFileRemove"
          :auto-upload="false"
          :file-list="fileList"
        >
          <el-button type="primary" :disabled="importLoading">
            <Icon icon="ep:upload" class="mr-5px" />
            点击上传
          </el-button>
          <template #tip>
            <div class="el-upload__tip">
              仅允许导入xls、xlsx格式文件。
              <el-link type="primary" :underline="false" style="font-size:12px;margin-left:10px" @click="importTemplate">
                下载模板
              </el-link>
            </div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" :loading="importLoading" @click="submitFileForm">确 定</el-button>
        <el-button @click="importDialogVisible = false">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { ClassDisciplineApi, ClassDiscipline } from '@/api/ao/classdiscipline'
import ClassDisciplineForm from './ClassDisciplineForm.vue'
import { Picture, Loading, Link } from '@element-plus/icons-vue'

/** 课堂纪律登记 列表 */
defineOptions({ name: 'ClassDiscipline' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<ClassDiscipline[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  fillTime: [],
  className: undefined,
  classSession: undefined,
  eveningSession: undefined,
  unbaggedPhones: undefined,
  absentCount: undefined,
  specialAbsentCount: undefined,
  isSalute: undefined,
  isRollCall: undefined,
  isAssignShowHomework: undefined,
  eveningHomeworkContent: undefined,
  remark: undefined,
  imageUrl: undefined,
  processStatus: undefined,
  filler: undefined,
  updateBy: undefined,
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const exportStatisticsLoading = ref(false) // 导出统计表的加载中

// 导入相关
const importDialogVisible = ref(false) // 导入对话框是否显示
const importLoading = ref(false) // 导入的加载中
const importFormRef = ref() // 导入表单Ref
const uploadRef = ref() // 上传组件Ref
const fileList = ref([]) // 文件列表
const importForm = reactive({
  updateSupport: false,
  file: undefined
})
const importRules = reactive({
  file: [{ required: true, message: '导入文件不能为空', trigger: 'change' }]
})
// 移除不需要的上传配置

/** 处理图片URL - 如果是相对路径则拼接完整地址 */
const getImageUrl = (url: string) => {
  if (!url) return ''
  
  // 过滤掉无效的URL文本
  const invalidTexts = ['该记录无图片', '无图片', '暂无', '无', '-', 'null', 'undefined']
  if (invalidTexts.some(text => url.includes(text))) {
    // console.log('无效URL文本，已过滤:', url)
    return ''
  }
  
  // 如果已经是完整URL（http或https开头），直接返回
  if (url.startsWith('http://') || url.startsWith('https://')) {
    // console.log('完整URL:', url)
    return url
  }
  
  // 如果是相对路径，拼接基础URL
  // 根据你的实际情况修改baseURL
  const baseURL = import.meta.env.VITE_BASE_URL || window.location.origin
  const fullUrl = `${baseURL}${url.startsWith('/') ? '' : '/'}${url}`
  console.log('拼接后的URL:', fullUrl, '原始URL:', url)
  return fullUrl
}

/** 在新标签页打开图片 */
const openImageInNewTab = (url: string) => {
  if (url) {
    window.open(url, '_blank')
  }
}

/** 根据填表时间判断是第几节课 */
const getClassSessionByTime = (fillTime: string) => {
  if (!fillTime) return '-'
  
  try {
    const date = new Date(fillTime)
    const hours = date.getHours()
    const minutes = date.getMinutes()
    const timeInMinutes = hours * 60 + minutes
    
    // 定义各节课的时间范围（转换为分钟）
    const timeRanges = [
      { name: '早读', start: 8 * 60 - 10, end: 8 * 60 + 20 },           // 8:00-8:20
      { name: '第1节', start: 8 * 60 + 20, end: 9 * 60 + 15 },      // 8:30-9:15
      { name: '第2节', start: 9 * 60 + 15, end: 10 * 60 + 10 },     // 9:25-10:10
      { name: '第3节', start: 10 * 60 + 20, end: 11 * 60 + 15 },    // 10:30-11:15
      { name: '第4节', start: 11 * 60 + 15, end: 12 * 60 + 10 },    // 11:25-12:10
      { name: '学习力', start: 14 * 60 - 10, end: 14 * 60 + 45 },         // 14:00-14:45
      { name: '第6节', start: 14 * 60 + 45, end: 15 * 60 + 40 },    // 14:55-15:40
      { name: '第7节', start: 16 * 60 - 20, end: 16 * 60 + 45 },         // 16:00-16:45
    ]
    
    // 查找匹配的时间段
    for (const range of timeRanges) {
      if (timeInMinutes >= range.start && timeInMinutes <= range.end) {
        return range.name
      }
    }
    
    return '-'
  } catch (error) {
    console.error('解析填表时间失败:', error)
    return '-'
  }
}

/** 根据填表时间判断是晚修第几节 */
const getEveningSessionByTime = (fillTime: string) => {
  if (!fillTime) return '-'
  
  try {
    const date = new Date(fillTime)
    const hours = date.getHours()
    const minutes = date.getMinutes()
    const timeInMinutes = hours * 60 + minutes
    
    // 定义晚修时间范围（转换为分钟）
    const eveningRanges = [
      { name: '第1节', start: 19 * 60, end: 19 * 60 + 45 },        // 19:00-19:45
      { name: '第2节', start: 19 * 60 + 55, end: 20 * 60 + 40 },   // 19:55-20:40
    ]
    
    // 查找匹配的时间段
    for (const range of eveningRanges) {
      if (timeInMinutes >= range.start && timeInMinutes <= range.end) {
        return range.name
      }
    }
    
    return '-'
  } catch (error) {
    console.error('解析填表时间失败:', error)
    return '-'
  }
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ClassDisciplineApi.getClassDisciplinePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ClassDisciplineApi.deleteClassDiscipline(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除课堂纪律登记 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await ClassDisciplineApi.deleteClassDisciplineList(checkedIds.value);
    message.success(t('common.delSuccess'))
    await getList();
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: ClassDiscipline[]) => {
  checkedIds.value = records.map((item) => item.id);
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ClassDisciplineApi.exportClassDiscipline(queryParams)
    download.excel(data, '课堂纪律登记.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 导出统计表 */
const handleExportStatistics = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportStatisticsLoading.value = true
    const data = await ClassDisciplineApi.exportStatistics(queryParams)
    download.excel(data, '课堂纪律统计表.xlsx')
  } catch {
  } finally {
    exportStatisticsLoading.value = false
  }
}

/** 导入模板操作 */
const importTemplate = async () => {
  const res = await ClassDisciplineApi.importTemplate()
  download.excel(res, '课堂纪律登记导入模板.xls')
}

/** 导入按钮操作 */
const handleImport = () => {
  importForm.updateSupport = false
  importForm.file = undefined
  fileList.value = []
  importDialogVisible.value = true
}

/** 提交上传文件 */
const submitFileForm = () => {
  importFormRef.value?.validate(async (valid: boolean) => {
    if (!valid) return
    const formData = new FormData()
    formData.append('updateSupport', importForm.updateSupport)
    formData.append('file', importForm.file)
    importLoading.value = true
    ClassDisciplineApi.importClassDiscipline(formData)
      .then((res) => {
        const data = res.data
        let text = '创建成功数量：' + data.createSuccessCount + '，'
        text += '更新成功数量：' + data.updateSuccessCount + '，'
        text += '失败数量：' + data.failureCount
        if (data.failureCount > 0) {
          text += '，失败数据如下：'
          data.failureList.forEach((item, index) => {
            text += '第' + item.rowIndex + '行：' + item.errorMsg + '；'
          })
        }
        message.alert(text)
        importDialogVisible.value = false
        fileList.value = []
        getList()
      })
      .finally(() => {
        importLoading.value = false
      })
  })
}

/** 文件选择成功处理 */
const handleFileSuccess = (file: any) => {
  importForm.file = file.raw
  fileList.value = [file]
}

/** 文件移除处理 */
const handleFileRemove = () => {
  importForm.file = undefined
  fileList.value = []
}

/** 文件上传失败处理 */
const handleFileError = () => {
  message.error('上传失败，请您重新上传！')
  importLoading.value = false
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>

<style scoped>
.image-slot {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 20px;
}
</style>